package com.huse.blog.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author llb
 * @version 1.0
 * @description: TODO
 * @date 2024/2/25 1:32
 * AOP处理日志
 * 我们希望在请求之前/方法调用之前获取、记录到相关参数信息 ip/请求者url 调用url 返回内容等等
 */
//springAop可以以一个切面的方式把web控制器的一个流切一刀 根据切面前后进行处理
@Aspect
@Component
public class LogAspect {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //定义一个切面
    @Pointcut("execution(* com.huse.blog.web.*.*(..))")//规定具体拦截那些类
    public void log(){}

    //在切面之前执行
    @Before("log()")//前端发起请求过来，这个切面都会横切web下的控制器
    public void doBefore(JoinPoint joinPoint){
        //拿到url ip等餐宿
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        RequestLog requestLog = new RequestLog(url,ip,classMethod,args);
        logger.info("++++++++++++++doBefore+++++++++++++");
        logger.info("Request : {}",requestLog);
    }

    @After("log()")
    public void doAfter(){
        logger.info("++++++++++++++doAfter+++++++++++++");
    }

    @AfterReturning(returning = "res",pointcut = "log()")
    public void doAfterReturn(Object res){
        //实现  返回内容
        logger.info("res:{}=======>"+res);
    }

    //定义一个内部类对象 请求参数对象
    private class RequestLog{
        private String url;
        private String ip;
        private String classMethod;
        private Object[] args;
        public RequestLog(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "RequestLog{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }

}
